﻿using ArienToolkits.ReflectionUnilities;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace ArienToolkits.DBUntilities.SqlServer.Extension
{
    /// <summary>
    /// 简单对象获取辅助类
    ///     <remarks>
    ///         后期可以扩展填写表名来获取对象或集合的方法
    ///     </remarks>
    /// </summary>
    public static class SimpleResultHelper
    {
        #region 获取原生数据类型单个值
        /// <summary>
        /// 获取原生数据类型单个值(如Int32，String等)
        /// </summary>
        /// <typeparam name="T">返回数据类型</typeparam>
        /// <param name="helper">数据库操作基础类</param>
        /// <param name="commandType">数据库操作类型</param>
        /// <param name="commandText">数据库操作语句</param>
        /// <param name="param">参数集合</param>
        /// <returns></returns>
        public static T GetSingleResult<T>(this ISqlHelper helper, CommandType commandType, string commandText, params SqlParameter[] param)
        {
            object tmpObjResult = helper.ExecuteScalar(commandType, commandText, param);

            if (tmpObjResult != null)
            {
                Type type = typeof(T);

                if (type.IsValueType)
                {
                    //如果是值类型
                    try
                    {
                        return (T)tmpObjResult;
                    }
                    catch { }
                }
                else
                {
                    //如果是引用类型
                    try
                    {
                        return (T)TypeConverter.ChangeType(type, tmpObjResult);
                    }
                    catch { }
                }
            }
            return default(T);
        }
        #endregion

        #region 获取单个简单对象
        /// <summary>
        /// 获取单个简单对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="helper">数据库操作辅助对象</param>
        /// <param name="condition">查询条件(可空)</param>
        /// <param name="fields">查询字段(可空)</param>
        /// <param name="param">查询参数(可空)</param>
        /// <returns></returns>
        public static T GetSimpleObject<T>(this ISqlHelper helper, string condition, string[] fields, params SqlParameter[] param)
        {
            //获取表名称
            Type targetType = typeof(T);
            T obj = Activator.CreateInstance<T>();
            string tableName = TableDataExtension.GetTableName(obj);

            if (!string.IsNullOrEmpty(condition))
            {
                if (!condition.StartsWith("WHERE", StringComparison.CurrentCultureIgnoreCase))
                {
                    condition = "WHERE " + condition;
                }
            }

            //拼接SQL语句
            string sql = string.Format("SELECT {0} FROM {1}(NOLOCK) {2}", GetFields(fields), tableName, condition);

            DataSet dataSet = helper.ExecuteFillDataSet(CommandType.Text, sql, param);

            //验证数据集
            if (Validator.IsNotNullOfDataSet(dataSet))
            {
                //返回指定类型数据
                return TypeConverter.ToObject<T>(dataSet.Tables[0].Rows[0]);
            }

            return default(T);
        }

        /// <summary>
        /// 获取单个简单对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="helper">数据库操作辅助对象</param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        public static T GetSimpleObject<T>(this ISqlHelper helper, SqlParameter param)
        {
            return GetSimpleObject<T>(helper, string.Format("WHERE {0}={1}", param.ParameterName.Substring(1), param.ParameterName), null, param);
        }
        #endregion

        #region 获取简单集合对象
        /// <summary>
        /// 查询简单集合对象
        /// </summary>
        /// <typeparam name="T">集合对象限定类型</typeparam>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static IList<T> GetSimpleList<T>(this ISqlHelper helper)
        {
            return GetSimpleList<T>(helper, string.Empty, string.Empty, null);
        }

        /// <summary>
        /// 查询简单集合对象
        /// </summary>
        /// <typeparam name="T">集合对象限定类型</typeparam>
        /// <param name="helper">数据库操作辅助对象</param>
        /// <param name="condition">查询条件(可空)</param>
        /// <param name="orderBy">查询排序条件</param>
        /// <param name="fields">查询字段(可空)</param>
        /// <param name="param">查询参数(可空)</param>
        /// <returns></returns>
        public static IList<T> GetSimpleList<T>(this ISqlHelper helper, string condition, string orderBy, string[] fields, params SqlParameter[] param)
        {
            //获取表名称
            Type targetType = typeof(T);
            T obj = Activator.CreateInstance<T>();
            string tableName = TableDataExtension.GetTableName(obj);

            string sql = string.Format("SELECT {0} FROM {1}(NOLOCK)", GetFields(fields), tableName, orderBy);

            //判断并追加条件
            if (!string.IsNullOrEmpty(condition))
            {
                sql += string.Format(" {0} {1} ", !condition.Trim().StartsWith("WHERE", StringComparison.CurrentCultureIgnoreCase) ? "WHERE" : string.Empty, condition);
            }

            //判断并追加排序
            if (!string.IsNullOrEmpty(orderBy))
            {
                sql += string.Format(" {0} {1} ", !condition.Trim().StartsWith("ORDER BY", StringComparison.CurrentCultureIgnoreCase) ? "ORDER BY" : string.Empty, orderBy);
            }

            DataSet dataSet = helper.ExecuteFillDataSet(CommandType.Text, sql, param);

            if (Validator.IsNotNullOfDataSet(dataSet))
            {
                return TypeConverter.ToList<T>(dataSet.Tables[0]);
            }

            return null;
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 获取字段列表
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="fieldAlias"></param>
        /// <returns></returns>
        private static string GetFields(string[] fields)
        {
            if (fields == null)
            {
                return " * ";
            }

            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < fields.Length; i++)
            {
                string field = fields[i];
                builder.AppendFormat(" {0} ,", field);
            }

            return builder.Remove(builder.Length - 1, 1).ToString();
        }
        #endregion
    }
}
